
using Microsoft.EntityFrameworkCore;
using StoreApp.Domain;

namespace StoreApp.Repository;

public class EfRepository<T> : IRepository<T> where T : class
{
    private readonly StoreDbContext _db;
    private readonly DbSet<T> _tb;
    public EfRepository(StoreDbContext db) {
        _db = db;
        _tb = _db.Set<T>();
    }
    public async Task<T> CreateAsync(T entity)
    {
        var obj = (await _tb.AddAsync(entity)).Entity;
        await _db.SaveChangesAsync();
        return obj;
    }

    public async Task DeleteAsync(T entity)
    {
        _tb.Remove(entity);
        await _db.SaveChangesAsync();
    }

    public async Task<List<T>> GetAllAsync()
    {
        var list = await _tb.ToListAsync();
        return list;
    }

    public async Task<T?> GetByIdAsync(int id)
    {
        var obj = await _tb.FindAsync(id);
        return obj;
    }

    public async Task UpdatAsync(T entity)
    {
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }
}